package com.childenglish.validation;

import com.childenglish.utils.DataEncryptionUtils;
import com.childenglish.utils.ValidationPatterns;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 加密邮箱验证器
 */
public class EncryptedEmailValidator implements ConstraintValidator<EncryptedEmail, String> {
    
    @Override
    public void initialize(EncryptedEmail constraintAnnotation) {
        // 初始化方法
    }
    
    @Override
    public boolean isValid(String encryptedEmail, ConstraintValidatorContext context) {
        // 如果值为空或null，则跳过验证
        if (encryptedEmail == null || encryptedEmail.trim().isEmpty()) {
            return true;
        }
        
        try {
            // 尝试解密
            String email = DataEncryptionUtils.decrypt(encryptedEmail);
            // 验证邮箱格式
            return ValidationPatterns.EMAIL_PATTERN.matcher(email).matches();
        } catch (Exception e) {
            // 如果解密失败，可能是明文，直接验证
            return ValidationPatterns.EMAIL_PATTERN.matcher(encryptedEmail).matches();
        }
    }
}

